module.exports = (sequelize, DataTypes) => {
    const Repair = sequelize.define(
        'Repair',
        {
            id: {
                type: DataTypes.BIGINT.UNSIGNED,
                allowNull: false,
                autoIncrement: true,
                primaryKey: true
            },
            fault: {
                type: DataTypes.STRING,
                allowNull: false,
                validate: {
                    notNull: {
                        msg: '故障不能为空'
                    }
                },
                comment: '故障描述'
            },
            detail: {
                type: DataTypes.STRING,
                comment: '修复方法'
            },
            date: {
                type: DataTypes.DATE,
                defaultValue: Date.now()
            },
            remark: {
                type: DataTypes.STRING,
                comment: '备注'
            },
            status: {
                type: DataTypes.TINYINT.UNSIGNED,
                allowNull: false,
                validate: {
                    notNull: {
                        msg: '状态不能为空'
                    }
                }
            },
            type: {
                type: DataTypes.TINYINT.UNSIGNED,
                defaultValue: 1,
                allowNull: false,
                validate: {
                    notNull: {
                        msg: '维修类型不能为空'
                    },
                    isIn: {
                        args: [[1, 2]],
                        msg: '维修类型错误'
                    }
                },
                comment: '维修类型:1.正常维修 2.厂商更换设备,需要替换原设备序列号'
            },
            serial: {
                type: DataTypes.STRING,
                validate: {
                    customValidator(value) {
                        if (value === null && this.type === 2) {
                            throw new Error('更换设备必须输入新设备序列号')
                        }
                    }
                },
                comment: '更换后设备序列号'
            },
            device_id: {
                type: DataTypes.BIGINT.UNSIGNED,
                allowNull: false,
                references: {
                    model: 'Device',
                    key: 'id'
                },
                validate: {
                    notNull: {
                        msg: '所属设备不能为空'
                    }
                },
                comment: '所属设备'
            }
        },
        {
            tableName: 'repair'
        }
    )

    Repair.associate = function(models) {
        models.Repair.belongsTo(models.Device, { foreignKey: 'device_id', targetKey: 'id' })
        models.Repair.hasMany(models.RepairPart, { foreignKey: 'repair_id', sourceKey: 'id' })
    }

    return Repair
}
